{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义测试数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test=[1,2,3,4,5,6,7,8,9,10,11,12]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "四分位数计算函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "#四分位数计算方法一（相当于Excel的QUARTILE.EXC方法）\n",
    "def quantile_exc(data, n):\n",
    "    if n<1 or n>3:\n",
    "        return false\n",
    "    data.sort()\n",
    "    position = (len(data) + 1)*n/4\n",
    "    pos_integer = int(math.modf(position)[1])\n",
    "    pos_decimal = position - pos_integer\n",
    "    quartile = data[pos_integer - 1] + (data[pos_integer] - data[pos_integer - 1])*pos_decimal\n",
    "    return quartile\n",
    "\n",
    "#四分位数计算方法二（相当于Excel的QUARTILE.INC方法）\n",
    "def quantile_inc(data, n):\n",
    "    if n<1 or n>3:\n",
    "        return false\n",
    "    data.sort()\n",
    "    position = 1 + (len(data)-1)*n/4\n",
    "    pos_integer = int(math.modf(position)[1])\n",
    "    pos_decimal = position - pos_integer\n",
    "    quartile = data[pos_integer - 1] + (data[pos_integer] - data[pos_integer - 1])*pos_decimal\n",
    "    return quartile"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "计算四分位距"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "IQR(1) = 6.5\n",
      "IQR(2) = 5.5\n"
     ]
    }
   ],
   "source": [
    "#第一种四分位数计算方法\n",
    "print('IQR(1) =',quantile_exc(data_test,3)-quantile_exc(data_test,1))\n",
    "#第二种四分位数计算方法\n",
    "print('IQR(2) =',quantile_inc(data_test,3)-quantile_inc(data_test,1))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
